package com.tanhua.server.service;

import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.dubbo.api.SoundApi;
import com.tanhua.dubbo.api.VideoApi;
import com.tanhua.dubbo.pojo.Sound;
import com.tanhua.dubbo.pojo.Video;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class SoundMQService {

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @DubboReference(version = "1.0.0")
    private SoundApi soundApi;

    /**
     * 发布语音消息
     *
     * @return
     */
    public Boolean soundMsg(String soundId) {
        return this.sendMsg(soundId, 1);
    }

    private Boolean sendMsg(String soundId, Integer type) {
        try {
            Sound sound = this.soundApi.querySoundById(soundId);
            //构建消息
            Map<String, Object> msg = new HashMap<>();
            msg.put("userId", UserThreadLocal.get());
            msg.put("soundId", soundId);
            msg.put("vid", sound.getVid());
            msg.put("type", type);

            //convertAndSend 输出时没有顺序，不需要等待，直接运行
            this.rocketMQTemplate.convertAndSend("tanhua-sound", msg);

        } catch (Exception e) {
            log.error("发送消息失败! soundId = " + soundId + ", type = " + type, e);
            return false;
        }

        return true;
    }

}
